﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Aandelendelen.Db
{
	internal static class DbCache
	{
		private const string cachedItemsKey = "cachedresultsets";

		internal static QueryBuilder GetQueryBuilder(string queryName)
		{
			string cacheName = "query_" + queryName;

			QueryBuilder queryBuilder = DbCache.Cache[cacheName] as QueryBuilder;

			if (queryBuilder == null)
			{
				queryBuilder = new QueryBuilder(queryName);

				CacheDependency dependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/DBQueries.xml"));

				DbCache.Cache.Insert(cacheName, queryBuilder, dependency);
			}

			return queryBuilder;
		}

		internal static Cache Cache
		{
			get { return HttpContext.Current.Cache; }
		}

		internal static void Add(CachedResult cachedResult)
		{
			CachedResultCollection cachedItems = Cache[cachedItemsKey] as CachedResultCollection;

			if (cachedItems == null)
			{
				cachedItems = new CachedResultCollection();

				Cache[cachedItemsKey] = cachedItems;
			}

			cachedItems[cachedResult.Key] = cachedResult;
		}

		internal static CachedResult Get(string key)
		{
			CachedResultCollection cachedItems = Cache[cachedItemsKey] as CachedResultCollection;

			if (cachedItems == null)
				return null;

			CachedResult result = null;
			cachedItems.TryGetValue(key, out result);

			return result;
		}

		internal static void ClearAffectedTableCache(StringCollection affectedTables)
		{
			if (affectedTables.Count == 0)
				return;

			CachedResultCollection cachedItems = Cache[cachedItemsKey] as CachedResultCollection;
			if (cachedItems == null)
				return;

			if (affectedTables[0] == "ALL")
			{
				Cache.Remove(cachedItemsKey);

				return;
			}

			foreach (CachedResult cached in cachedItems.Values)
			{
				foreach (string affectedTable in affectedTables)
				{
					if (cached.DependentTables.Contains(affectedTable))
					{
						Cache.Remove(cached.Key);
						break;
					}
				}
			}
		}

	}
}
